package com.guchenbo.example.dfs;

/**
 * @author guchenbo
 * @date 2024/8/21
 */

import java.util.*;

public class DependencyResolver {

    // 使用栈来实现遍历依赖关系
    public static Set<String> findAllDependencies(String item, Map<String, List<String>> dependencyMap) {
        Set<String> dependencies = new HashSet<>(); // 用于保存所有依赖
        Stack<String> stack = new Stack<>(); // 栈用于存储需要处理的元素

        // 将初始元素压入栈
        stack.push(item);

        // 当栈不为空时，继续处理
        while (!stack.isEmpty()) {
            String currentItem = stack.pop(); // 弹出栈顶元素

            // 获取当前元素的直接依赖
            List<String> directDependencies = dependencyMap.get(currentItem);
            if (directDependencies != null) {
                for (String dependency : directDependencies) {
                    if (dependencies.add(dependency)) { // 如果依赖没有被添加过
                        stack.push(dependency); // 将该依赖压入栈，处理它的依赖
                    }
                }
            }
        }

        return dependencies;
    }

    public static void main(String[] args) {
        // 定义依赖关系
        Map<String, List<String>> dependencyMap = new HashMap<>();
        dependencyMap.put("A", Arrays.asList("B", "C"));
        dependencyMap.put("B", Arrays.asList("C", "D"));
        dependencyMap.put("C", Arrays.asList("E"));
        dependencyMap.put("D", Arrays.asList("F"));
        dependencyMap.put("E", Arrays.asList("F", "G"));
        dependencyMap.put("F", Arrays.asList("H"));

        // 示例 List 集合
        List<String> items = Arrays.asList("A", "B");

        // 计算每个元素的所有依赖
        for (String item : items) {
            Set<String> allDependencies = findAllDependencies(item, dependencyMap);
            System.out.println("Item: " + item + ", Dependencies: " + allDependencies);
        }

        ViewNodeUtils.buildViewNodeMapAndSort(items, dependencyMap::get).forEach((k, v) -> {
            v.forEach(System.out::println);
        });

        dependencyMap.put("v1", Arrays.asList("v2", "v3", "v4"));
        dependencyMap.put("v2", Arrays.asList("v5", "v6"));
        dependencyMap.put("v3", Arrays.asList("v6"));
        dependencyMap.put("v6", Arrays.asList("v4"));

        ViewNodeUtils.buildViewNodeMapAndSort(Arrays.asList("v1"), dependencyMap::get).forEach((k, v) -> {
            v.forEach(System.out::println);
        });
    }
}

